package com.pactera.asmp.server.schedule;

import com.alibaba.fastjson.JSONObject;
import com.pactera.asmp.server.common.email.IMailService;
import com.pactera.asmp.server.common.logprint.utils.CollectionUtils;
import com.pactera.asmp.server.dao.IssueMapper;
import com.pactera.asmp.server.dao.MasterComputerMapper;
import com.pactera.asmp.server.dao.ProjectMapper;
import com.pactera.asmp.server.dao.UserMapper;
import com.pactera.asmp.server.entity.IssueSearchDTO;
import com.pactera.asmp.server.entity.ProjectMasterDeviceVo;
import com.pactera.asmp.server.pdf.PdfProjectTestReport;
import com.pactera.asmp.server.pojo.DeviceIssueInfo;
import com.pactera.asmp.server.pojo.ProjectInfo;
import com.pactera.asmp.server.pojo.User;
import com.pactera.asmp.server.pojo.IssueReportInfo;
import com.pactera.asmp.server.vo.DeviceTraceInfo;
import com.pactera.asmp.server.vo.TraceReportEmailVo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
@EnableScheduling
public class TraceReportEmailSchedule {

    private Logger logger = LoggerFactory.getLogger(TraceReportEmailSchedule.class);

    private static final String TEMPLATE_FILENAME = "asmp_email_trace_report_template.html";

    @Autowired
    private IMailService emailService;

    @Autowired
    private IssueMapper issueMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private MasterComputerMapper masterComputerMapper;

    @Autowired
    private UserMapper userMapper;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    private SimpleDateFormat simpleDateFormatForDetail = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * every day执行一次
     */
    //@Scheduled(cron = "0 0 0/24 * * ?")
    @Scheduled(cron = "0 0/15 * * * ?")
    public void sendEmail(){
        IssueSearchDTO issueSearchDTO = new IssueSearchDTO();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date startDate = calendar.getTime();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) +1);
        Date endDate = calendar.getTime();
        issueSearchDTO.setIssueCreateTime(simpleDateFormat.format(startDate));
        issueSearchDTO.setIssueCreateTimeEnd(simpleDateFormat.format(endDate));
        //test
        logger.info("{},{}", simpleDateFormat.format(startDate), simpleDateFormat.format(endDate));
        String startDateStr = simpleDateFormat.format(startDate);
        String endDateStr = simpleDateFormat.format(endDate);
//        issueSearchDTO.setIssueCreateTime("2023-01-25");
//        issueSearchDTO.setIssueCreateTimeEnd("2024-01-25");
        List<IssueReportInfo> issueReportInfos = issueMapper.reportIssue(issueSearchDTO);
        if(CollectionUtils.isEmpty(issueReportInfos)){
            return;
        }
        HashMap<String, TraceReportEmailVo> traceReportMap = new HashMap<>();
        logger.info("issueReportInfos={}",JSONObject.toJSONString(issueReportInfos));
        for(IssueReportInfo issueReport : issueReportInfos) {
            TraceReportEmailVo emailVo = traceReportMap.get(issueReport.getProjectName());
            if(emailVo == null) {
                ProjectInfo projectInfo = projectMapper.selectByName(issueReport.getProjectName());
                if(projectInfo == null){
                    continue;
                }
                emailVo = new TraceReportEmailVo();
                traceReportMap.put(issueReport.getProjectName(), emailVo);
                List<ProjectMasterDeviceVo> projectMasterDeviceVos = masterComputerMapper.mastercBindByProjectId(projectInfo.getId());
                String masterNames = "";
                if (!CollectionUtils.isEmpty(projectMasterDeviceVos)) {
                    for (ProjectMasterDeviceVo projectMasterDeviceVo : projectMasterDeviceVos) {
                        if(!masterNames.contains(projectMasterDeviceVo.getMasterComputer().getName())) {
                            masterNames = masterNames.concat(",").concat(projectMasterDeviceVo.getMasterComputer().getName());
                        }
                    }
                    masterNames = masterNames.substring(1);
                }
                emailVo.setMasterNames(masterNames);
                emailVo.setProjectId(projectInfo.getId());
                emailVo.setProjectName(issueReport.getProjectName());
                emailVo.setUserId(projectInfo.getCreateUserId());
                emailVo.setStartDate(startDateStr + " 00:00:00");
                emailVo.setEndDate(endDateStr + " 23:59:59");
                emailVo.setCurrentTime( simpleDateFormatForDetail.format(new Date()));
            }
            if("Crash".equals(issueReport.getIssueType())){
                emailVo.setCrash(issueReport.getIssueCount());
            }else if("ANR".equals(issueReport.getIssueType())){
                emailVo.setAnr(issueReport.getIssueCount());
            }else {
                emailVo.setOther(emailVo.getOther()+ issueReport.getIssueCount());
            }
        }
        logger.info("traceReportMap size:{}", traceReportMap.size());
        for(TraceReportEmailVo emailVo: traceReportMap.values()){
            logger.info("emailVo={}",JSONObject.toJSONString(emailVo));
            User createUser = userMapper.findUserById(emailVo.getUserId());
            if(createUser == null){
                logger.info(" email user is null userId={} ",  emailVo.getUserId());
                continue;
            }
            logger.info(" EmailList  email ={} ",  createUser.getEmail());
            List<String> toEmailList = new ArrayList<>();
            toEmailList.add(createUser.getEmail());
            String[] toEmails = toEmailList.toArray(new String[toEmailList.size()]);
            String[] ccEmails = new String[]{};
            String[] attachmentPath = new String[]{};
            List<DeviceTraceInfo> traceList = new ArrayList<>();
            List<DeviceIssueInfo> deviceIssueInfos = issueMapper.reportDeviceIssue(issueSearchDTO);
            if(CollectionUtils.isEmpty(deviceIssueInfos)){
                continue;
            }
            HashMap<String, DeviceTraceInfo> deviceReportMap = new HashMap<>();
            logger.info("deviceIssueInfos={}",JSONObject.toJSONString(deviceIssueInfos));
            for(DeviceIssueInfo issueInfo : deviceIssueInfos) {
                String key = issueInfo.getIssueProcessName()+issueInfo.getVinCode();
                DeviceTraceInfo deviceTraceInfo = deviceReportMap.get(key);
                if(deviceTraceInfo == null) {
                    deviceTraceInfo = new DeviceTraceInfo();
                    deviceReportMap.put(key, deviceTraceInfo);

                    deviceTraceInfo.setIssueProcessName(issueInfo.getIssueProcessName());
                    deviceTraceInfo.setVinCode(issueInfo.getVinCode());

                }
                if("Crash".equals(issueInfo.getIssueType())){
                    deviceTraceInfo.setCrash(issueInfo.getIssueCount());
                    deviceTraceInfo.setLastCrashTime(issueInfo.getLastTime());
                }else if("ANR".equals(issueInfo.getIssueType())){
                    deviceTraceInfo.setAnr(issueInfo.getIssueCount());
                    deviceTraceInfo.setLastAnrTime(issueInfo.getLastTime());
                }else {
                    deviceTraceInfo.setOther(deviceTraceInfo.getOther()+ issueInfo.getIssueCount());
                    deviceTraceInfo.setLastAnrTime(issueInfo.getLastTime());
                }
            }
            traceList.addAll(deviceReportMap.values());
            logger.info(" traceList ={} ",  JSONObject.toJSONString(traceList));
            try {
                Map<String, Object> dataMap = JSONObject.parseObject(JSONObject.toJSONString(emailVo),Map.class);
                File pdfFile = PdfProjectTestReport.generateTraceFile(dataMap, traceList,false, null);
                // 邮件标题
                String subject = String.format("%s_%s", emailVo.getProjectName(),
                        simpleDateFormat.format(startDate));
                log.info("email subject:{}", subject);
                emailService.sendBatchMailByTemplate(toEmails, ccEmails, subject,
                        attachmentPath, TEMPLATE_FILENAME, dataMap, pdfFile, emailVo.getProjectName());
                logger.info("=====success=====EmailList  email ={} ",  createUser.getEmail());
            } catch (Exception e) {
                log.error("email trace report error: ", e);
            }
        }
    }
}
